﻿namespace Vibstudio.NetConfigurator.Engine.Configuration
{
	#region Namespaces
	
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Xml.Linq;

    using Vibstudio.NetConfigurator.Common;
    using Vibstudio.NetConfigurator.Extensions;
    using Vibstudio.NetConfigurator.Model;

	#endregion
	
    [Obfuscation(Exclude = true, ApplyToMembers = false)]
    internal class DomainConfigurator : IConfiguration
    {
        #region Public Methods and Operators

        public bool Configure(string filePath, List<ConfigurationSetting> settings)
        {
            XDocument document = XDocument.Load(filePath);

            bool configured = ChangeDomain(document, settings);
            if (configured)
            {
                document.Save(filePath);
            }

            return configured;
        }

        public void Reset()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Methods

        private bool ChangeDomain(XDocument document, List<ConfigurationSetting> settings)
        {
            bool domainChanged = true;

            
            try
            {
                XElement element =
                    document
                        .Descendants("authentication")
                        .Where(e =>
                            {
                                XAttribute modeAttribute = e.Attribute("mode");
                                return modeAttribute != null && modeAttribute.Value.ToLower() == "forms";
                            })
                        .Elements("forms")
                        .FirstOrDefault();
                
                string domain = GetDomain(settings);
                string defaultUrl = element.Attribute("defaultUrl").Value.ReplaceDomain(domain);

                element.Attribute("domain").SetValue(domain);
                element.Attribute("defaultUrl").SetValue(defaultUrl);
            }
            catch
            {
                domainChanged = false;
            }

            return domainChanged;
        }

        private string GetDomain(List<ConfigurationSetting> settings)
        {
            try
            {
                return settings[0].Value;
            }
            catch
            {
                return string.Empty;
            }
        }

        #endregion
    }
}